import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';

class SignUpController extends GetxController with GetSingleTickerProviderStateMixin {
  /// 响应式成员变量
  final _isPhone = false.obs;

  set isPhone(value) => _isPhone.value = value;

  get isPhone => _isPhone.value;

  final _isChecked = false.obs;

  set isChecked(value) => _isChecked.value = value;

  get isChecked => _isChecked.value;

  final _secondsRemaining = 0.obs;

  set secondsRemaining(value) => _secondsRemaining.value = value;

  get secondsRemaining => _secondsRemaining.value;

  /// 成员变量
  // tab 页标题
  late final List<String> tabTitles;
  late final TabController tabController;

  late String dialCode;
  late TextEditingController accountController;
  late TextEditingController passwordController;
  late TextEditingController verificationCodeController;
  late TextEditingController invitationCodeController;

  late Timer? _timer;

  /// 事件
  Future<void> sendVerificationCode() async {
    if (secondsRemaining != 0) {
      toast('Resend after $secondsRemaining seconds');
      return;
    }
    if (accountController.text.isEmpty) {
      toast('Phone or email empty'.tr);
      return;
    }
    if (tabController.index == 0 && !duIsEmail(accountController.text)) {
      toast('Bad email format'.tr);
      return;
    }
    Loading.show();
    await Request()
        .post(
      '/userConfig/sendCode',
      {
        'email': accountController.text,
        'mobile': accountController.text,
        'mobileType': dialCode,
        'sendType': 1,
      }..removeWhere((key, value) =>
          (tabController.index == 1 && key == 'email') || // tab 1 只能输入 mobile
          (tabController.index == 0 && (key == 'mobile' || key == 'mobileType'))), // tab 0 只能输入 email
    )
        .then((_) {
      startCountdown();
      toast('Success');
    });
  }

  void startCountdown() {
    secondsRemaining = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (secondsRemaining > 0) {
        secondsRemaining--;
      } else {
        timer.cancel();
      }
    });
  }

  void stopCountdown() {
    _timer?.cancel();
  }

  Future<void> register() async {
    if (accountController.text.isEmpty) {
      toast('Phone or email empty'.tr);
      return;
    }
    if (tabController.index == 0 && !duIsEmail(accountController.text)) {
      toast('Bad email format'.tr);
      return;
    }
    if (passwordController.text.isEmpty) {
      toast('Password empty'.tr);
      return;
    }
    if (verificationCodeController.text.isEmpty) {
      toast('Verification code empty'.tr);
      return;
    }
    if (!isChecked) {
      toast('请同意用户协议'); //TODO 修改提示语
      return;
    }
    Loading.show();
    await Request()
        .post(
      '/user/register',
      {
        'email': accountController.text,
        'mobile': accountController.text,
        'mobileType': dialCode,
        'password': passwordController.text,
        'validateCode': verificationCodeController.text,
        'inviteCode': invitationCodeController.text,
      }..removeWhere((key, value) =>
          value.isEmpty || // 值为空
          (tabController.index == 1 && key == 'email') || // tab 1 只能输入 mobile
          (tabController.index == 0 && (key == 'mobile' || key == 'mobileType'))), // tab 0 只能输入 email
    )
        .then((_) {
      toast('Success');
      Get.offAllNamed(Routes.SIGN_IN);
    });
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    // 准备一些静态数据
    tabTitles = ['Email'.tr, 'Phone number'.tr];
    tabController = TabController(length: tabTitles.length, vsync: this)
      ..addListener(() {
        isPhone = tabController.index == 1;
        accountController.clear();
        Get.focusScope?.unfocus();
      });

    dialCode = ConfigStore.to.countryCode;
    accountController = TextEditingController();
    passwordController = TextEditingController();
    verificationCodeController = TextEditingController();
    invitationCodeController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    stopCountdown();
  }
}
